# -*- coding: utf-8 -*-
# @Time: 2021/11/27 15:02
# @Author: jiuwu
# @Email: 2359196586@qq.com
# @File: serializers.py
# @Software: PyCharm
from rest_framework import serializers
from rest_framework.fields import SerializerMethodField
from rest_framework.serializers import ModelSerializer

from community.models import Article, Comment


class ArticleSerializer(ModelSerializer):
    user_name = serializers.CharField(source='user.first_name', read_only=True)
    user_avatar = serializers.CharField(source='user.userdetail.avatrar', read_only=True)

    class Meta:
        model = Article
        exclude = ['is_delete']


class CommentSerializer(ModelSerializer):
    user_name = serializers.CharField(source='user.first_name', read_only=True)
    user_avatar = serializers.CharField(source='user.userdetail.avatrar', read_only=True)
    reply_username = SerializerMethodField()

    class Meta:
        model = Comment
        fields = '__all__'

    def get_reply_username(self, comment):
        reply_user_name = Comment.objects.get(id=comment.reply_comment).user.first_name
        return reply_user_name


class CommentDetailSerializer(ModelSerializer):
    user_name = serializers.CharField(source='user.first_name', read_only=True)
    user_avatar = serializers.CharField(source='user.userdetail.avatrar', read_only=True)
    sonComment = SerializerMethodField()

    class Meta:
        model = Comment
        fields = '__all__'

    def get_sonComment(self, comment):
        serializer = CommentSerializer(Comment.objects.filter(parent_comment=comment.id), many=True)
        data = serializer.data
        data.reverse()  # 让列表反序
        return data
